package com.myfoon.servlet.pub;

import com.myfoon.model.entity.Photo;
import com.myfoon.model.entity.User;

import com.myfoon.model.entity.Video;

import java.io.File;
import java.io.IOException;

import java.io.PrintWriter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.json.JSONObject;

public class UploadVideo extends HttpServlet {
    private final static String directory = "/var/www/html/u";      // Uploads Real Directory
    private final static String webDir = "/u";                      // Web Directory    
    private final static String vDirectory = "videos"; // Photos Directory    
    private final static String tmpDirectory = "tmp"; // Photos Directory    
    
    public UploadVideo() {
    }

    @Override
    protected void doPost(HttpServletRequest httpServletRequest,
                          HttpServletResponse httpServletResponse) throws ServletException,
                                                                          IOException {
        User user = (User)httpServletRequest.getSession(true).getAttribute("user");      
        List<Video> videoList = null;        
        
        if (httpServletRequest.getSession(true).getAttribute("attachedVideos") != null) {            
            videoList = (List<Photo>)httpServletRequest.getSession(true).getAttribute("attachedVideos");
        }
        else {
            videoList = new ArrayList<Video>();
        }
        
        httpServletResponse.setContentType("text/plain");                
                
        String userDir = directory + "/" + vDirectory + "/" + user.getId().toString() + "/";         
        String userTmp = directory + "/" + tmpDirectory + "/" + user.getId().toString() + "/";
        String fileName = String.valueOf(System.currentTimeMillis());        
                        
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
                        
        new File(userDir).mkdirs();        
        new File(userTmp).mkdirs();
        factory.setRepository(new File(userTmp));
        
        ServletFileUpload upload = new ServletFileUpload(factory);                
        upload.setSizeMax(5000000);
                            
        try {
            List fileItems = upload.parseRequest(httpServletRequest);
            Iterator iter = fileItems.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem)iter.next();

                if (item.isFormField()) {

                } else {                                                                
                    System.out.println("Content Type: " + item.getContentType());                    
                    System.out.println("Name: " + item.getName());
                    System.out.println("Size: " + item.getSize());
                    System.out.println("Field Name: " + item.getFieldName());                    
                    File file = new File(userDir, fileName);                                          
                    item.write(file);  
                    
                    
                    JSONObject object = new JSONObject();
                    object.put("f_id", fileName);
                    object.put("f_type", "video");                    
                    object.put("f_name", item.getName());                    
                    object.put("f_url", webDir + "/" + vDirectory + "/" + user.getId().toString() + "/" + fileName);
                    
                    PrintWriter writer = httpServletResponse.getWriter();    
                    writer.println(object.toString());
                    
                    Video video = new Video();
                    video.setTempId(fileName);
                    video.setOwner(user);
                    video.setSrc(webDir + "/" + vDirectory + "/" + user.getId().toString() + "/" + fileName);
                    video.setSrcsmall(webDir + "/" + vDirectory + "/" + user.getId().toString() + "/" + fileName);                
                    
                    videoList.add(video);        
                    httpServletRequest.getSession(true).setAttribute("attachedImages", videoList);                                        
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }    
    }
}
